package shop.cart.controller;


import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import shop.cart.service.CartService;
import shop.common.core.Result;
import shop.common.entity.Cart;

import java.util.List;

@RestController
@RequestMapping("/api/carts")
@RequiredArgsConstructor
public class CartController {

    private final CartService cartService;

    @GetMapping("/test")
    public Result test() {
        return Result.ok().data("test");
    }

    @PostMapping("/increase/{userId}/{productId}")
    public Result increase(@PathVariable String userId, @PathVariable String productId) {
        cartService.increase(userId, productId);
        return Result.ok();
    }

    @PostMapping("/decrease/{userId}/{productId}")
    public Result decrease(@PathVariable String userId, @PathVariable String productId) {
        cartService.decrease(userId, productId);
        return Result.ok();
    }

    @PostMapping("/select/{id}")
    public Result select( @PathVariable String id) {
        cartService.select(id);
        return Result.ok();
    }

    @PostMapping("/create")
    public Result create(@RequestBody Cart cart) {
        boolean save = cartService.save(cart);
        return save ? Result.ok() : Result.fail();
    }


    @DeleteMapping("/delete/{id}")
    public Result remove(@PathVariable("id") String id) {
        boolean flag = cartService.removeById(id);
        return flag ? Result.ok() : Result.fail();
    }

    @DeleteMapping("/delete/{userId}/{productId}")
    public Result removeByUserIdAndProductId(@PathVariable("userId") String userId, @PathVariable("productId") String productId) {
        boolean flag = cartService.removeByUserIdAndProductId(userId,productId);
        return flag ? Result.ok() : Result.fail();
    }



    @DeleteMapping("/clear/{userId}")
    public Result clear(@PathVariable("userId") String userId) {
        boolean flag = cartService.clearByUserId(userId);
        return flag ? Result.ok() : Result.fail();
    }

    @PutMapping("/update")
    public Result update(@RequestBody Cart cart) {
        boolean bool = cartService.updateById(cart);
        return bool ? Result.ok() : Result.fail();
    }


    @GetMapping("/details/{id}")
    public Result details(@PathVariable String id) {
        Cart cart = cartService.getById(id);
        return Result.ok().data(cart);
    }


    @PostMapping("/list/{userId}")
    public Result list(@PathVariable String userId) {
        List<Cart> list = cartService.listByUserId(userId);
        return Result.ok().data(list);
    }


}
